<template>
  <u-popup 
    :show="show" 
    @close="onClose"
    mode="bottom"
    :round="20"
    :closeable="false"
  >
    <view class="tag-selector">
      <!-- 头部 -->
      <view class="selector-header">
        <text class="clear-btn" @click="onClear">清除</text>
        <text class="title">用工筛选</text>
        <view class="confirm-section">
          <text class="confirm-btn" @click="onConfirm">确定</text>
          <u-icon name="close" size="24" color="#999999" @click="onClose"></u-icon>
        </view>
      </view>
      
      <!-- 内容区域 -->
      <view class="selector-content">
        <!-- 左侧分类列表 -->
        <scroll-view class="category-list" scroll-y="true">
          <view 
            v-for="category in categories" 
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <text class="category-name">{{ category.name }}</text>
          </view>
        </scroll-view>
        
        <!-- 右侧标签列表 -->
        <scroll-view 
          class="tag-list" 
          scroll-y="true"
          :scroll-into-view="scrollIntoView"
          :scroll-with-animation="true"
          @scroll="onTagListScroll"
        >
          <view 
            v-for="(category, categoryIndex) in categories" 
            :key="category.id"
            class="tag-section"
            :id="`section-${category.id}`"
          >
            <!-- 分类标题 -->
            <view class="section-title">
              <text class="title-text">{{ category.name }}</text>
            </view>
            
            <!-- 该分类下的标签 -->
            <view class="section-tags">
              <view 
                v-for="tag in tagsData[category.id]" 
                :key="tag.id"
                class="tag-item"
                :class="{ 
                  active: selectedTags.includes(tag.id)
                }"
                @click="toggleTag(tag.id)"
              >
                <text class="tag-name">{{ tag.name }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { systemApi } from '@/api/api-helper.js'

const props = defineProps({
  show: Boolean,
  modelValue: {
    type: Array as () => string[],
    default: () => []
  }
})

const emit = defineEmits(['update:show', 'update:modelValue', 'confirm'])

// 分类数据
const categories = ref([
  { id: 'job-activity', name: '岗位活动' },
  { id: 'dining-accommodation', name: '餐饮住宿' },
  { id: 'job-subsidy', name: '岗位补贴' },
  { id: 'work-environment', name: '工衣环境' },
  { id: 'work-method', name: '作业方式' },
  { id: 'shift-arrangement', name: '班次安排' },
  { id: 'medical-exam', name: '入职体检' },
  { id: 'salary-benefits', name: '薪资福利' },
  { id: 'workplace-facilities', name: '工作设施' }
])

// 標籤數據
const tagsData = ref({
  'job-activity': [],
  'dining-accommodation': [],
  'job-subsidy': [],
  'work-environment': [],
  'work-method': [],
  'shift-arrangement': [],
  'medical-exam': [],
  'salary-benefits': [],
  'workplace-facilities': []
})

const selectedCategory = ref('job-activity')
const selectedTags = ref<string[]>([]) // 存儲選中的標籤ID
const selectedTagCodes = ref<string[]>([]) // 存儲選中的標籤enCode
const isLoading = ref(false)
const scrollIntoView = ref('') // 控制滾動到指定位置

// 当前显示的标签列表
const currentTags = computed(() => {
  return tagsData.value[selectedCategory.value] || []
})

// 获取所有标签数据
const allTagsData = computed(() => {
  return tagsData.value
})

// 加載標籤數據
async function loadTagData() {
  try {
    isLoading.value = true
    
    // 調用接口獲取企業特徵標籤數據
    		const res: any = await systemApi.getListByTypeDataCode('enterpriseFeatures')
    
    if (res && res.code === 200) {
      const list = res.data || []
      
      // 清空現有數據
      Object.keys(tagsData.value).forEach(key => {
        tagsData.value[key] = []
      })
      
      // 將標籤數據分配到對應分類
      list.forEach((item: any) => {
        // 根據標籤的enCode或fullName來分類
        const tagData = {
          id: item.id,
          name: item.fullName || item.name || item.label || item.text,
          enCode: item.enCode,
          description: item.description,
          sortCode: item.sortCode,
          enabledMark: item.enabledMark
        }
        
        // 根據標籤內容智能分類
        const category = categorizeTag(tagData)
        if (category && tagsData.value[category]) {
          tagsData.value[category].push(tagData)
        }
      })
      
      // 如果沒有數據，使用默認的硬編碼數據作為備用
      if (list.length === 0) {
        loadDefaultTagData()
      }
    } else {
      console.warn('獲取標籤數據失敗，使用默認數據')
      loadDefaultTagData()
    }
  } catch (error) {
    console.error('加載標籤數據出錯:', error)
    loadDefaultTagData()
  } finally {
    isLoading.value = false
  }
}

// 加載默認的硬編碼標籤數據
function loadDefaultTagData() {
  tagsData.value = {
    'job-activity': [
      { id: 'reimburse-travel', name: '报销车费' },
      { id: 'group-activity', name: '拼团活动' },
      { id: 'advance-payment', name: '可借支' }
    ],
    'dining-accommodation': [
      { id: 'meals-included', name: '包吃' },
      { id: 'accommodation-included', name: '包住' },
      { id: 'card-payment', name: '刷卡吃饭' },
      { id: 'eat-first-deduct', name: '先吃后扣' }
    ],
    'job-subsidy': [
      { id: 'meal-subsidy', name: '餐饮补贴' },
      { id: 'medical-subsidy', name: '体检费补贴' },
      { id: 'stable-job-subsidy', name: '稳岗补贴' },
      { id: 'accommodation-subsidy', name: '住宿补贴' },
      { id: 'transport-subsidy', name: '交通补贴' },
      { id: 'phone-subsidy', name: '话费补贴' },
      { id: 'overtime-subsidy', name: '加班补贴' },
      { id: 'holiday-subsidy', name: '节日补贴' }
    ],
    'work-environment': [
      { id: 'air-conditioned', name: '空调宿舍' },
      { id: 'work-uniform', name: '工衣提供' },
      { id: 'safety-equipment', name: '劳保用品' },
      { id: 'clean-environment', name: '清洁环境' },
      { id: 'modern-facility', name: '现代化设施' },
      { id: 'heating-system', name: '供暖系统' },
      { id: 'ventilation-system', name: '通风系统' },
      { id: 'lighting-system', name: '照明系统' }
    ],
    'work-method': [
      { id: 'assembly-line', name: '流水线' },
      { id: 'independent-work', name: '独立岗位' },
      { id: 'team-work', name: '团队协作' },
      { id: 'quality-control', name: '质检岗位' },
      { id: 'packaging', name: '包装岗位' },
      { id: 'warehouse', name: '仓库管理' },
      { id: 'maintenance', name: '设备维护' },
      { id: 'technical-support', name: '技术支持' },
      { id: 'customer-service', name: '客服岗位' }
    ],
    'shift-arrangement': [
      { id: 'day-shift', name: '白班' },
      { id: 'night-shift', name: '夜班' },
      { id: 'rotating-shift', name: '轮班' },
      { id: 'flexible-time', name: '弹性时间' },
      { id: 'overtime-available', name: '可加班' },
      { id: 'weekend-work', name: '周末工作' },
      { id: 'holiday-work', name: '节假日工作' },
      { id: 'part-time', name: '兼职岗位' },
      { id: 'full-time', name: '全职岗位' }
    ],
    'medical-exam': [
      { id: 'medical-reimbursement', name: '报销体检费' },
      { id: 'on-site-medical', name: '现场体检' },
      { id: 'medical-insurance', name: '医疗保险' },
      { id: 'health-check', name: '健康检查' },
      { id: 'vaccination', name: '疫苗接种' },
      { id: 'dental-check', name: '牙科检查' },
      { id: 'vision-check', name: '视力检查' },
      { id: 'physical-exam', name: '体格检查' }
    ],
    'salary-benefits': [
      { id: 'high-salary', name: '高薪岗位' },
      { id: 'performance-bonus', name: '绩效奖金' },
      { id: 'holiday-bonus', name: '节日福利' },
      { id: 'annual-leave', name: '年假福利' },
      { id: 'social-security', name: '社保缴纳' },
      { id: 'housing-fund', name: '住房公积金' },
      { id: 'unemployment-insurance', name: '失业保险' },
      { id: 'work-injury-insurance', name: '工伤保险' },
      { id: 'maternity-insurance', name: '生育保险' }
    ],
    'workplace-facilities': [
      { id: 'free-wifi', name: '免费WiFi' },
      { id: 'parking-space', name: '停车位' },
      { id: 'canteen', name: '员工食堂' },
      { id: 'break-room', name: '休息室' },
      { id: 'shower-room', name: '淋浴间' },
      { id: 'locker-room', name: '更衣室' },
      { id: 'gym', name: '健身房' },
      { id: 'library', name: '图书室' },
      { id: 'game-room', name: '娱乐室' },
      { id: 'nursing-room', name: '母婴室' }
    ]
  }
}

// 根據標籤內容智能分類
function categorizeTag(tag: any): string | null {
  const name = tag.name?.toLowerCase() || ''
  const enCode = tag.enCode?.toLowerCase() || ''
  
  // 崗位活動相關
  if (name.includes('活動') || name.includes('拼團') || name.includes('借支') || 
      name.includes('報銷') || name.includes('車費') || enCode.includes('activity')) {
    return 'job-activity'
  }
  
  // 餐飲住宿相關
  if (name.includes('包吃') || name.includes('包住') || name.includes('刷卡') || 
      name.includes('吃飯') || name.includes('住宿') || enCode.includes('dining') || 
      enCode.includes('accommodation')) {
    return 'dining-accommodation'
  }
  
  // 崗位補貼相關
  if (name.includes('補貼') || name.includes('津貼') || name.includes('補助') || 
      enCode.includes('subsidy')) {
    return 'job-subsidy'
  }
  
  // 工衣環境相關
  if (name.includes('工衣') || name.includes('空調') || name.includes('宿舍') || 
      name.includes('勞保') || name.includes('清潔') || name.includes('現代化') || 
      name.includes('供暖') || name.includes('通風') || name.includes('照明') || 
      enCode.includes('environment') || enCode.includes('uniform')) {
    return 'work-environment'
  }
  
  // 作業方式相關
  if (name.includes('流水線') || name.includes('獨立') || name.includes('團隊') || 
      name.includes('質檢') || name.includes('包裝') || name.includes('倉庫') || 
      name.includes('維護') || name.includes('技術') || name.includes('客服') || 
      enCode.includes('method') || enCode.includes('work')) {
    return 'work-method'
  }
  
  // 班次安排相關
  if (name.includes('白班') || name.includes('夜班') || name.includes('輪班') || 
      name.includes('彈性') || name.includes('加班') || name.includes('週末') || 
      name.includes('節假日') || name.includes('兼職') || name.includes('全職') || 
      enCode.includes('shift') || enCode.includes('time')) {
    return 'shift-arrangement'
  }
  
  // 入職體檢相關
  if (name.includes('體檢') || name.includes('醫療') || name.includes('健康') || 
      name.includes('疫苗') || name.includes('牙科') || name.includes('視力') || 
      name.includes('免費體檢') || enCode.includes('medical') || enCode.includes('exam') ||
      enCode.includes('physical')) {
    return 'medical-exam'
  }
  
  // 薪資福利相關
  if (name.includes('高薪') || name.includes('獎金') || name.includes('福利') || 
      name.includes('年假') || name.includes('社保') || name.includes('住房') || 
      name.includes('失業') || name.includes('工傷') || name.includes('生育') || 
      enCode.includes('salary') || enCode.includes('benefits') || enCode.includes('insurance')) {
    return 'salary-benefits'
  }
  
  // 工作設施相關
  if (name.includes('wifi') || name.includes('停車') || name.includes('食堂') || 
      name.includes('休息') || name.includes('淋浴') || name.includes('更衣') || 
      name.includes('健身') || name.includes('圖書') || name.includes('娛樂') || 
      name.includes('母嬰') || enCode.includes('facilities') || enCode.includes('wifi')) {
    return 'workplace-facilities'
  }
  
  // 如果無法分類，默認放到崗位活動
  return 'job-activity'
}

// 組件掛載時加載標籤數據
onMounted(() => {
  loadTagData()
})

// 監聽彈窗顯示狀態，當顯示時重新加載數據
watch(() => props.show, (val) => {
  if (val) {
    loadTagData()
  }
})

function onClose() {
  emit('update:show', false)
}

function onClear() {
  selectedTags.value = []
  selectedTagCodes.value = []
}

// 根據選中的標籤ID獲取對應的enCode數組
function getSelectedTagCodes(): string[] {
  const codes: string[] = []
  
  // 遍歷所有分類的標籤數據
  Object.values(tagsData.value).forEach(categoryTags => {
    categoryTags.forEach(tag => {
      if (selectedTags.value.includes(tag.id)) {
        codes.push(tag.enCode)
      }
    })
  })
  
  return codes
}

function onConfirm() {
  // 根據選中的標籤ID獲取對應的enCode
  const selectedCodes = getSelectedTagCodes()
  
  emit('update:modelValue', selectedCodes) // 傳遞enCode數組
  emit('confirm', selectedCodes) // 傳遞enCode數組
  emit('update:show', false)
}

function selectCategory(categoryId: string) {
  selectedCategory.value = categoryId
  
  // 設置滾動到對應的分類區域
  scrollIntoView.value = `section-${categoryId}`
  
  // 延遲一下再清空，確保滾動完成
  setTimeout(() => {
    scrollIntoView.value = ''
  }, 500)
}

// 監聽標籤列表滾動，自動更新左側導航選中狀態
function onTagListScroll(e: any) {
  // 這裡可以實現滾動時自動更新左側導航的選中狀態
  // 由於uni-app的scroll事件限制，暫時不實現自動同步
  // 可以根據需要後續優化
}

function toggleTag(tagId: string) {
  const index = selectedTags.value.indexOf(tagId)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tagId)
  }
  
  // 同步更新enCode數組
  selectedTagCodes.value = getSelectedTagCodes()
}

// 監聽外部傳入的選中值
watch(() => props.modelValue, (newValue) => {
  if (newValue && Array.isArray(newValue)) {
    // 如果外部傳入的是enCode數組，需要反向查找對應的標籤ID
    const tagIds: string[] = []
    
    Object.values(tagsData.value).forEach(categoryTags => {
      categoryTags.forEach(tag => {
        if (newValue.includes(tag.enCode)) {
          tagIds.push(tag.id)
        }
      })
    })
    
    selectedTags.value = tagIds
    selectedTagCodes.value = [...newValue]
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.tag-selector {
  background-color: #F8F8F8;
  border-radius: 20rpx 20rpx 0 0;
  min-height: 900rpx;
  height: 85vh;
}

.selector-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #EEEEEE;
  background-color: #FFFFFF;
  
  .clear-btn {
    font-size: 28rpx;
    color: #666666;
  }
  
  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .confirm-section {
    display: flex;
    align-items: center;
    gap: 20rpx;
    
    .confirm-btn {
      font-size: 28rpx;
      color: var(--u-primary);
      font-weight: 500;
    }
  }
}

.selector-content {
  display: flex;
  height: calc(100vh - 200rpx);
  background-color: #F8F8F8;
}

.category-list {
  width: 220rpx;
  background-color: #FFFFFF;
  height: 100%;
  
  .category-item {
    padding: 35rpx 25rpx;
    background-color: #FFFFFF;
    flex-shrink: 0;
    position: relative;
    
    .category-name {
      font-size: 30rpx;
      color: #666666;
    }
    
    &.active {
      background-color: #F8F8F8;
      
      .category-name {
        color: var(--u-primary);
        font-weight: 500;
      }
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 40rpx;
        background-color: var(--u-primary);
        border-radius: 0 4rpx 4rpx 0;
      }
    }
  }
}

.tag-list {
  flex: 1;
  padding: 25rpx;
  height: 100%;
  overflow-y: auto;
  scroll-behavior: smooth; /* 添加平滑滾動 */
  
  .tag-section {
    margin-bottom: 40rpx;
    scroll-margin-top: 20rpx; /* 滾動時的頂部邊距 */
    
    &:last-child {
      margin-bottom: 20rpx;
    }
  }
  
  .section-title {
    margin-bottom: 20rpx;
    
    .title-text {
      font-size: 30rpx;
      font-weight: bold;
      color: #333333;
    }
  }
  
  .section-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 30rpx;
    margin-bottom: 30rpx;
  }
  
  .tag-item {
    display: inline-block;
    padding: 25rpx 30rpx;
	line-height: 1;
    border: 2rpx solid #fff;
    border-radius: 8rpx;
    background-color: #FFFFFF;
    flex-shrink: 0;
    min-width: 120rpx;
    text-align: center;
    
    .tag-name {
      font-size: 26rpx;
      color: #333333;
      line-height: 1.2;
    }
    
    &.active {
      border-color: var(--u-primary);
      background-color: #FFF5F0;
      
      .tag-name {
        color: var(--u-primary);
        font-weight: 500;
      }
    }
  }
}
</style> 